package com.ruoyi.common.utils.poi.word.render;

import lombok.Data;
import org.apache.poi.xwpf.usermodel.*;
import java.util.List;

/**
 * 没有key的表格渲染
 */
@Data
public class PoiDataTableRowNoKey extends PoiDataBeforeCreateWord {
    /**
     * 表格index
     */
    protected int tableIndex;
    /**
     * 表格index
     */
    protected int rowCopyNum;
    /**
     * 值
     */
    protected List<List> value;

    /**
     * 构造方法
     */
    public PoiDataTableRowNoKey(int tableIndex, int rowCopyNum, List<List> value) {
        this.tableIndex = tableIndex;
        this.rowCopyNum = rowCopyNum;
        this.value = value;
    }

    @Override
    public void handle(XWPFDocument document) throws Exception {
        super.handle(document);
        if (document.getTables().size() <= tableIndex) {
            return;
        }
        XWPFTable table = document.getTables().get(tableIndex);
        int insertRow = rowCopyNum + 1;
        for (int j = 0; j < value.size(); j++) {
            XWPFTableRow targetRow = table.insertNewTableRow(insertRow);
            XWPFTableRow copyRows = table.getRow(rowCopyNum); //复制行
            targetRow.getCtRow().setTrPr(copyRows.getCtRow().getTrPr());

            List<XWPFTableCell> copyCells = copyRows.getTableCells();
            //复制列对象
            XWPFTableCell targetCell = null;
            for (int i = 0; i < copyCells.size(); i++) {
                XWPFTableCell copyCell = copyCells.get(i);
                targetCell = targetRow.addNewTableCell();
                targetCell.getCTTc().setTcPr(copyCell.getCTTc().getTcPr());

                XWPFRun cellR = targetCell.getParagraphs().get(0).createRun();
                cellR.setText(value.get(j).get(i) == null ? "" : String.valueOf(value.get(j).get(i)));
            }
            insertRow++;
        }
        //删掉第一行的空白行
        table.removeRow(rowCopyNum);
    }
}
